<!-- 内容弹框 -->
<template>
  <div>
    <el-dialog class="dialog" :title="title" :visible.sync="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="clickModalFn" @closed="loading = false">

      <div class="dialog__body">
        <el-scrollbar>
          <div class="dialog__body__item" :style="{ maxHeight: maxHeight + 'px' }">
            <slot />
          </div>
        </el-scrollbar>
      </div>

      <span slot="footer" v-if="footer">
        <el-button @click="dialogVisible = false" v-if="cancelText" :disabled="loading">{{cancelText}}</el-button>
        <el-button type="primary" @click="submit" :loading="loading">{{loading?'请求中':sureText}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'dialog',
  props: {
    // 头部信息
    title: {
      type: String,
      default: '提示',
    },
    // 是否展示fotter
    footer: {
      type: Boolean,
      default: true
    },
    // 展示的双向数据绑定
    value: {
      type: Boolean,
      default: false,
    },
    // 点击遮罩层关闭
    clickModal: {
      type: Boolean,
      default: true,
    },
    sureText: {
      type: String,
      default: '确 定'
    },
    cancelText: {
      type: String,
      default: '取 消'
    },
    // 点击确认
    sureFn: {
      type: Function
    },
  },
  data() {
    return {
      dialogVisible: false,

      loading: false,
      maxHeight: 640, // 内容弹框body体默认高度
    };
  },
  computed: {
    clickModalFn() {
      if (!this.clickModal) return false
      return !this.loading
    }
  },
  watch: {
    value(n) {
      if (n === this.dialogVisible) return
      this.dialogVisible = n
    },
    dialogVisible(n) {
      if (n === this.value) return
      this.$emit('input', n)
    }
  },
  mounted() {
    this.changeDialogBodyHeight()
    window.addEventListener('resize', this.changeDialogBodyHeight)
  },
  destroyed() {
    window.removeEventListener('resize', this.changeDialogBodyHeight)
  },
  methods: {
    // 获取屏幕可视高度,改变弹框内容体的高度
    changeDialogBodyHeight() {
      const height = document.documentElement.clientHeight
      const headerFooterHeight = 54 + 70 + 40 // 弹框头部+底部+内边距
      const padding = 100 // 弹框上下间距
      const fixed = headerFooterHeight + padding
      this.maxHeight = height - fixed
    },
    submit() {
      this.loading = true
      this.sureFn(this.cb)
    },
    // 关闭回调，消息提示
    cb(message, type = "info") {
      this.dialogVisible = false

      if (!message) return
      this.$message({
        message: message,
        type: type
      });
    }
  },
}
</script>
<style lang='scss' scoped>
.dialog {
  ::v-deep .el-dialog {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto !important;
    height: fit-content;
    width: fit-content;
    .el-dialog__body {
      padding: 0;
    }
  }

  &__body {
    padding: 20px 0 20px 30px;
    &__item {
      padding-right: 30px;
    }
  }
}
</style>